package com.demo.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.function.Function;

/**
 * SqlSession 和事务的相关操作
 */
public class DaoUtils {
    private static SqlSessionFactory factory;

    static {
        //在静态代码块中 直接读取 Mybatis 配置文件
        String resource = "sqlMapConfig.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("读取 sqlMapConfig.xml 失败");
            System.exit(1);
        }
        factory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    public static <R> R execute(Function<SqlSession, R> function) {
        //创建SqlSession
        SqlSession sqlSession = factory.openSession();
        try {
            //将外部传入的匿名函数 进行调用
            R result = function.apply(sqlSession);
            //提交事务
            sqlSession.commit();
            return result;
        } catch (Throwable t) {
            //出现异常和错误时 回滚事务
            sqlSession.rollback();
            System.err.println("执行错误！");
            throw t;
        } finally {
            sqlSession.close();
        }
    }

}
